package org.tlipoca.smarticletagrelational.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;

@MappedTypes(ArrayList.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ListTypeHandler extends BaseTypeHandler<ArrayList<Long>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, ArrayList<Long> parameter, JdbcType jdbcType) throws SQLException {
        String ids = parameter.stream().map(Object::toString).collect(Collectors.joining(","));
        ps.setString(i, ids);
    }

    @Override
    public ArrayList<Long> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String ids = rs.getString(columnName);
        return (ArrayList<Long>) Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList());
    }

    @Override
    public ArrayList<Long> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String ids = rs.getString(columnIndex);
        return (ArrayList<Long>) Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList());
    }

    @Override
    public ArrayList<Long> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String ids = cs.getString(columnIndex);
        return (ArrayList<Long>) Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toList());
    }
}
